package com.crazydream.wechat.security.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;

import com.crazydream.wechat.security.exception.MethodErrorException;
import com.crazydream.wechat.security.exception.ValidateCodeException;

/**
 * spring security登录失败处理
 * 
 * @author shadow
 * @email 124010356@qq.com
 * @create 2012.04.28
 */
public class LoginFailureHandler implements AuthenticationFailureHandler {
	
	private String loginUrl ;

	public void onAuthenticationFailure(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException ex)
			throws IOException, ServletException {
		if (ex instanceof UsernameNotFoundException) {
			// 账号错误
			request.setAttribute("error", ex.getMessage());
		} else if (ex instanceof BadCredentialsException) {
			// 密码错误
			request.setAttribute("error", "用户名/密码错误,请重新输入!");
		} else if (ex instanceof ValidateCodeException) {
			// 验证码错误
			request.setAttribute("error",ex.getMessage());
		} else if (ex instanceof MethodErrorException) {
			// 请求方法错误
			request.setAttribute("error", "请求方法错误!");
		} else if (ex instanceof SessionAuthenticationException) {
			// 登陆超时错误
			response.sendRedirect(request.getContextPath() + "/server/error/timeout.jsp");
		} else {
			// 未知异常错误
			response.getWriter().print("未知异常错误,请联系相关技术人员!");
		}
		request.getRequestDispatcher(loginUrl).forward(request, response);
	}

	public String getLoginUrl() {
		return loginUrl;
	}

	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}
	
}
